#!/usr/bin/env node

require('dotenv').config();
const Client = require('ftp');
const chalk = require('chalk');

class PHPStormStyleTest {
    constructor() {
        this.host = process.env.FTP_HOST;
        this.port = parseInt(process.env.FTP_PORT) || 21;
        this.user = process.env.FTP_USER;
        this.password = process.env.FTP_PASSWORD;
    }

    async testPHPStormConfig() {
        console.log(chalk.blue('🎯 模拟PHPStorm的FTP配置测试'));
        console.log(chalk.gray('=' .repeat(50)));
        console.log(chalk.cyan(`主机: ${this.host}:${this.port}`));
        console.log(chalk.cyan(`用户: ${this.user}`));
        console.log(chalk.cyan('模式: 主动模式 (非被动模式)'));
        console.log('');

        return new Promise((resolve) => {
            const client = new Client();
            let connectionSuccessful = false;

            // 设置严格的主动模式配置，类似PHPStorm
            const config = {
                host: this.host,
                port: this.port,
                user: this.user,
                password: this.password,
                // 关键配置：严格主动模式
                passive: false,
                // 更短的超时时间，类似IDE的行为
                connTimeout: 20000,
                pasvTimeout: 20000,
                // 禁用keepalive，使用更简单的连接
                keepalive: 0,
                // 设置调试模式查看详细交互
                debug: console.log
            };

            console.log(chalk.yellow('尝试连接...'));

            client.on('ready', () => {
                connectionSuccessful = true;
                console.log(chalk.green('✓ FTP连接建立成功'));

                // 测试目录操作，类似IDE的行为
                console.log(chalk.blue('测试目录列表...'));
                client.list('/', (err, list) => {
                    if (err) {
                        console.log(chalk.red(`❌ 目录列表失败: ${err.message}`));
                    } else {
                        console.log(chalk.green(`✓ 目录列表成功，找到 ${list.length} 个项目`));
                        list.slice(0, 3).forEach(item => {
                            console.log(chalk.gray(`  ${item.type} ${item.name}`));
                        });
                    }

                    // 现在测试文件上传
                    this.testUploadWithActiveMode(client, resolve);
                });
            });

            client.on('error', (err) => {
                console.log(chalk.red(`❌ 连接失败: ${err.message}`));
                if (!connectionSuccessful) {
                    // 尝试fallback配置
                    console.log(chalk.yellow('\n尝试fallback配置...'));
                    this.testFallbackConfig(resolve);
                } else {
                    resolve(false);
                }
            });

            client.on('close', (hadError) => {
                if (hadError && !connectionSuccessful) {
                    console.log(chalk.yellow('连接意外关闭，尝试替代配置...'));
                    this.testFallbackConfig(resolve);
                }
            });

            console.log(chalk.gray('连接配置:'), config);
            client.connect(config);
        });
    }

    testUploadWithActiveMode(client, resolve) {
        console.log(chalk.blue('\n测试文件上传...'));

        // 创建一个临时测试文件
        const fs = require('fs');
        const testContent = `PHPStorm风格测试文件\n时间戳: ${new Date().toISOString()}\n测试内容: Hello World!`;
        fs.writeFileSync('./phpstorm-test.txt', testContent);

        const uploadTimeout = setTimeout(() => {
            console.log(chalk.red('❌ 上传超时(20秒)'));
            client.destroy();
            resolve(false);
        }, 20000);

        client.put('./phpstorm-test.txt', '/phpstorm-test.txt', (err) => {
            clearTimeout(uploadTimeout);
            
            if (err) {
                console.log(chalk.red(`❌ 文件上传失败: ${err.message}`));
                console.log(chalk.red(`错误详情: ${err.code || 'N/A'}`));
                
                // 尝试诊断错误类型
                if (err.message.includes('data connection')) {
                    console.log(chalk.yellow('💡 这是数据连接问题，尝试不同配置...'));
                    client.end();
                    this.testAlternativeMode(resolve);
                    return;
                }
                
                client.end();
                resolve(false);
            } else {
                console.log(chalk.green('✅ 文件上传成功!'));
                
                // 验证上传结果
                client.size('/phpstorm-test.txt', (sizeErr, size) => {
                    if (!sizeErr) {
                        console.log(chalk.green(`✓ 验证成功，文件大小: ${size} 字节`));
                    }
                    
                    client.end();
                    resolve(true);
                });
            }
        });
    }

    async testFallbackConfig(resolve) {
        console.log(chalk.yellow('尝试fallback配置 (更宽松的设置)...'));
        
        const client = new Client();
        
        // 更宽松的配置
        const fallbackConfig = {
            host: this.host,
            port: this.port,
            user: this.user,
            password: this.password,
            passive: false,
            connTimeout: 30000,
            pasvTimeout: 30000,
            keepalive: 30000,
            // 添加更多选项
            secure: false,
            secureOptions: { rejectUnauthorized: false }
        };

        client.on('ready', () => {
            console.log(chalk.green('✓ Fallback连接成功'));
            this.testUploadWithActiveMode(client, resolve);
        });

        client.on('error', (err) => {
            console.log(chalk.red(`❌ Fallback也失败: ${err.message}`));
            resolve(false);
        });

        client.connect(fallbackConfig);
    }

    async testAlternativeMode(resolve) {
        console.log(chalk.yellow('\n尝试替代配置组合...'));
        
        const alternatives = [
            { name: '纯主动模式', passive: false, connTimeout: 15000 },
            { name: '主动模式+无keepalive', passive: false, keepalive: 0, connTimeout: 15000 },
            { name: '主动模式+TLS关闭', passive: false, secure: false, connTimeout: 15000 }
        ];

        for (const alt of alternatives) {
            console.log(chalk.cyan(`测试: ${alt.name}`));
            
            const success = await this.testSingleAlternative(alt);
            if (success) {
                console.log(chalk.green(`✅ ${alt.name} 上传成功!`));
                resolve(true);
                return;
            }
        }
        
        console.log(chalk.red('❌ 所有替代方案都失败了'));
        resolve(false);
    }

    async testSingleAlternative(config) {
        return new Promise((resolve) => {
            const client = new Client();
            let resolved = false;

            const timeout = setTimeout(() => {
                if (!resolved) {
                    resolved = true;
                    client.destroy();
                    resolve(false);
                }
            }, 25000);

            client.on('ready', () => {
                client.put('./phpstorm-test.txt', `/test-${Date.now()}.txt`, (err) => {
                    clearTimeout(timeout);
                    if (!resolved) {
                        resolved = true;
                        client.end();
                        resolve(!err);
                    }
                });
            });

            client.on('error', () => {
                clearTimeout(timeout);
                if (!resolved) {
                    resolved = true;
                    resolve(false);
                }
            });

            const fullConfig = {
                host: this.host,
                port: this.port,
                user: this.user,
                password: this.password,
                ...config
            };

            client.connect(fullConfig);
        });
    }
}

if (require.main === module) {
    const test = new PHPStormStyleTest();
    test.testPHPStormConfig()
        .then(success => {
            if (success) {
                console.log(chalk.green('\n🎉 成功找到可工作的配置!'));
            } else {
                console.log(chalk.red('\n💔 未能找到可工作的配置'));
            }
            process.exit(success ? 0 : 1);
        })
        .catch(console.error);
}

module.exports = PHPStormStyleTest;